package com.sgcc.pda.ssal.mqtt.proxy.server;

import com.hzwq.codec.config.SSALConfigInitProperties;
import com.hzwq.codec.encrypt.EncryptHandler;
import com.sgcc.pda.baselibrary.utils.LogUtil;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * Created by cj on 2020/1/10.
 * mqtt的本地代理服务，在本地开启服务，拦截paho框架发出的mqtt报文。
 * 转成ssal报文
 * 通过代理客户端的channel再发到前置。
 */
public class MqttProxyServer {

    private static final String TAG = "mqtt";
    public static Channel serverChannel;
    public static boolean isStarted = false;

    public static synchronized void startServer() {
        if(isStarted) return;
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workGroup).channel(NioServerSocketChannel.class)
                //保持连接数
                .option(ChannelOption.SO_BACKLOG, 128)
                //有数据立即发送
                .option(ChannelOption.TCP_NODELAY, true)
                //保持连接
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
//                        pipeline.addLast("mqttdecoder",MqttEncoder.INSTANCE);
                        pipeline.addLast("mqttServerHandler", new MqttServerHandler(new EncryptHandler()));

                    }
                });

        try {
            ChannelFuture future = serverBootstrap.bind(SSALConfigInitProperties.MQTT_PROXY_HOST, SSALConfigInitProperties.MQTT_PROXY_PORT).sync();
            if (future.isSuccess()) {
                 serverChannel = future.channel();
                LogUtil.e(TAG, "代理服务已启动成功！！！");
                isStarted = true;
            } else {
                LogUtil.e(TAG, "新代理服务启动失败！！！");
            }
            future.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
            isStarted = false;
            LogUtil.e(TAG, "startServer: " + e.getMessage());
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
            LogUtil.e(TAG, "代理服务已关闭！！！");
            isStarted = false;
        }

    }

    public static void sendMessage(Object msg) {
        if (serverChannel != null) {
            serverChannel.writeAndFlush(msg);
        }
    }


}
